class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        if (fruits.size() == 1)
            return 1;
        unordered_map<int, int> map;
        int left = 0;
        int right = 0;
        int len = 0;
        while (right < fruits.size())
        {
            if (map.size() <= 2)
            {
                map[fruits[right]]++;
                right++;
                if (map.size() == 2)
                    len = max(len, right - left);
            }
            else
            {
                map[fruits[left]]--;
                if (map[fruits[left]] == 0)
                    map.erase(fruits[left]);
                left++;
            }
        }
        if (len == 0 && fruits.size() != 0)
            return fruits.size();
        return len;
    }
};